package com.example.myapplication5.viewmodel

import android.content.Context
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myapplication5.entity.Todo
import com.example.myapplication5.service.AppDatabase
import com.example.myapplication5.service.TodoDao
import com.example.myapplication5.service.TodoService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class ListViewModel(dao: TodoDao) : ViewModel() {

    //数据列表
    var list by mutableStateOf<List<Todo>>(listOf())
        private set

    //toast 内容
    private val toastContent = MutableSharedFlow<String>()
    val toast = toastContent.asSharedFlow()

    //loading  状态
    var loading by mutableStateOf(true)

    //    private val db = AppDatabase.getInstance(context)
    private val service = TodoService(dao)

    fun fetchList() {
        viewModelScope.launch {
//            withContext(Dispatchers.IO) {
//                Thread.sleep(1000)
//            }
            loading = true
            list = service.getAll()
            loading = false
        }
    }


    fun done(item: Todo, it: Boolean) {
        viewModelScope.launch {
            list.map { todo ->
                var new = todo
                if (todo.id == item.id) {
                    new = todo.copy(done = it)
                    new
                }
            }
            toastContent.emit("${item.content.substring(0, minOf(8, item.content.length))}事项完成")
//        toastContent="${item.content.substring(0, minOf(8,item.content.length))}事项完成"

        }
    }
}